package com.sunyard.manage.controller;

import com.alibaba.fastjson.JSON;
import com.sunyard.constant.ErrMessageConst;
import com.sunyard.constant.manage.RoleConst;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.bo.role.RoleAddBO;
import com.sunyard.dal.bo.role.RoleDeleteBO;
import com.sunyard.dal.bo.role.RolePopedomConfigBO;
import com.sunyard.dal.bo.role.RolePopedomQueryBO;
import com.sunyard.dal.bo.role.RoleQueryBO;
import com.sunyard.dal.bo.role.RoleUpdateBO;
import com.sunyard.dal.dto.RoleDTO;
import com.sunyard.dal.entity.Role;
import com.sunyard.dal.mapper.RoleMapper;
import com.sunyard.enums.PopedomEnum;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.manage.service.PopedomService;
import com.sunyard.manage.service.RoleService;
import com.sunyard.utils.ExcelOutput;
import com.sunyard.utils.PrimaryKeyUtil;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.Response.HeaderResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * @author jiy.fang
 * @ClassName RoleController
 * @Description description
 * @date 2019/7/24 11:08
 */
@Slf4j
@Api(tags = "RoleController", description = "角色管理")
@RestController
@RequestMapping(value = "/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PopedomService popedomService;

    @Autowired
    private OperatorLogService operatorLogService;

    @Value("${operator.role.id}")
    private String operatorRole;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * @Description: 角色管理
     * @Author: jiy.fang
     * @Date: 2019/7/24 11:21
     */
    @ApiOperation(value = "分页查询角色信息")
    @PostMapping(value = "/showRole")
    @ResponseBody
    public BaseResult<DataGrid<RoleDTO>> queryRole(HttpServletRequest request, @RequestBody PaginationBO<RoleQueryBO> queryBO) {
        try {
            return roleService.queryRoleByPage(request, queryBO);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 角色添加
     * @Author: jiy.fang
     * @Date: 2019/7/24 20:22
     */
    @ApiOperation(value = "添加角色信息")
    @PostMapping(value = "/addRole")
    @ResponseBody
    public BaseResult addRole(HttpServletRequest request, @Valid @RequestBody RoleAddBO roleAddBO) {
        try {
            String auditId = PrimaryKeyUtil.getPrimaryKey();
            //添加角色审核
            roleAddBO.setRoleId(PrimaryKeyUtil.getPrimaryKey(RoleConst.ROLE_ID));
            roleAddBO .setAuditId(auditId);
            BaseResult baseResult = roleService.insertRole(request, roleAddBO);
            //角色审核成功前 分配权限到角色权限临时表
            RolePopedomConfigBO rolePopedomConfigBO = new RolePopedomConfigBO();
            rolePopedomConfigBO.setRoleId(roleAddBO.getRoleId());
            rolePopedomConfigBO.setPopedomList(roleAddBO.getPopedomList());
            roleService.configRolePopedom(roleAddBO.getAuditType(), rolePopedomConfigBO, auditId);
            // popedomService.addRolePopedom(request, rolePopedomConfigBO);
            return baseResult;
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }


    /**
     * @Description: 角色修改
     * @Author: jiy.fang
     * @Date: 2019/7/24 20:24
     */
    @ApiOperation(value = "角色修改")
    @PostMapping(value = "/updateRole")
    @ResponseBody
    public BaseResult<GetResult> updateRole(HttpServletRequest request, @Valid @RequestBody RoleUpdateBO updateBO) {
        try {
            return roleService.updateRole(request, updateBO);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 角色删除
     * @Author: jiy.fang
     * @Date: 2019/7/24 20:35
     */
    @ApiOperation(value = "角色删除")
    @PostMapping(value = "/deleteRole")
    @ResponseBody
    public BaseResult deleteRole(HttpServletRequest request, @Valid @RequestBody RoleDeleteBO roleDeleteBO) {
        try {
            return roleService.deleteRole(request, roleDeleteBO);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 角色批量删除
     * @Author: jiy.fang
     * @Date: 2019/7/24 20:35
     */
    @ApiOperation(value = "角色批量删除")
    @PostMapping(value = "/batchDeleteRole")
    @ResponseBody
    public BaseResult batchDeleteRole(HttpServletRequest request, @Valid @RequestBody RoleDeleteBO roleDeleteBO) {
        try {
            return roleService.batchDeleteRole(request, roleDeleteBO);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 获取所属角色下拉列表框
     * @Author: jiy.fang
     * @Date: 2019/7/26 14:26
     */
    @ApiOperation(value = "获取所属角色下拉列表框")
    @PostMapping(value = "/getRoleLists")
    @ResponseBody
    public BaseResult<List<Role>> getRoleLists(HttpServletRequest request) {
        try {
            List<Role> roles = roleService.getRoleLists(request);
            return GetResult.getResult(roles);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 查询权限树
     * @Author: jiy.fang
     * @Date: 2019/7/24 18:01
     */
    @ApiOperation(value = "查询角色待分配权限")
    @PostMapping(value = "/queryRolePopodom")
    @ResponseBody
    public BaseResult queryRolePopodom(HttpServletRequest request, @Valid @RequestBody RolePopedomQueryBO popedomQueryBO) {
        try {
            return popedomService.findRolePopedomTreeByOpId(request, popedomQueryBO);
        } catch (Exception e) {
            log.error("系统异常", e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 角色已拥有的权限
     * @Author: jiy.fang
     * @Date: 2019/8/5 15:30
     */
    @ApiOperation(value = "角色已拥有的权限")
    @PostMapping(value = "/findAllpopedom")
    @ResponseBody
    public BaseResult findAllpopedom() {
        try {
            return popedomService.findAllpopedom();
        } catch (Exception e) {
            log.error("系统异常", e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 角色已拥有的权限
     * @Author: jiy.fang
     * @Date: 2019/8/5 15:30
     */
    @ApiOperation(value = "角色已拥有的权限")
    @PostMapping(value = "/queryRoleOwnPopodom")
    @ResponseBody
    public BaseResult queryRoleOwnPopodom(@Valid @RequestBody RolePopedomQueryBO popedomQueryBO) {
        try {
            return popedomService.findRoleOwnPopedomTreeByRoleId(popedomQueryBO.getRoleId());
        } catch (Exception e) {
            log.error("系统异常", e);
            return GetResult.getResultErr();
        }
    }

    /**
     * @Description: 角色导出
     * @Author: chengy.wei
     * @Date: 2019/7/22 23:20
     */
    @ApiOperation("导出角色信息")
    @ResponseBody
    @PostMapping(value = "/export")
    public void exportOrganization(@RequestBody PaginationBO<RoleQueryBO> queryBO, HttpServletResponse response, HttpServletRequest request) {
        try {
            RoleQueryBO roleQueryBO = queryBO.getParams();
            log.info("角色信息查询入参：{}", JSON.toJSONString(roleQueryBO));
            String orgId = TokenUtil.getOrgId(request.getHeader("token"));
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            String opName = TokenUtil.getOpName(request.getHeader("token"));
            operatorLogService.insert("用户"+opName+"角色信息导出", "角色导出", "1", opId, opName, orgId);
            if (null == roleQueryBO.getOrgId() || "".equals(roleQueryBO.getOrgId())) {
                roleQueryBO.setOrgId(orgId);
            }
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("roleName", roleQueryBO.getRoleName());
            queryMap.put("operatorRole", operatorRole);
            //执行查询
            List<RoleDTO> roleList = roleMapper.getRoleListByPage(queryMap);
            if (roleList == null || roleList.isEmpty()) {
                throw new RuntimeException("无数据无需导出");
            }
            String title = "角色信息导出" + Math.random() + ".xls";
            String[] headers = new String[]{"角色ID", "角色名称", "创建人", "状态"};

            List<Object[]> dataList;

            dataList = roleList.stream().map(roleDTO -> {
                Object[] obj = new Object[headers.length];
                obj[0] = roleDTO.getRoleId();
                obj[1] = roleDTO.getRoleName();
                obj[2] = roleDTO.getCreateOp();
                obj[3] = roleDTO.getAuditStatus();
                return obj;
            }).collect(toList());
            OutputStream out = null;
            // 防止中文乱码
            String headStr = "attachment; filename=\"" + new String(title.getBytes("gb2312"), "ISO8859-1") + "\"";
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            ExcelOutput ex = new ExcelOutput(title, headers, dataList);
            ex.export(out);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            HeaderResult.setFailHeader(request, response, e.getMessage());
        }
    }


    @ApiOperation(value = "获取拥有开锁权限的角色列表")
    @PostMapping(value = "/getOpenLockRoles")
    @ResponseBody
    public BaseResult<List<Role>> getOpenLockRoles(HttpServletRequest request) {
        try {
            List<Role> roles = roleService.getOpenLockRoles(PopedomEnum.OPENLOCK.getPopemdomId(),request);
            return GetResult.getResult(roles);
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

}
